package com.xhh.reapply.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.utils.thread.ThreadLocalUtil;
import com.xhh.apis.check.ICheckClient;
import com.xhh.apis.user.IUserClient;
import com.xhh.common.constants.CheckedConstants;
import com.xhh.common.constants.ReapplyConstants;
import com.xhh.model.check.vos.CheckedVo;
import com.xhh.model.common.dtos.PageResponseResult;
import com.xhh.model.common.dtos.ResponseResult;
import com.xhh.model.common.enums.AppHttpCodeEnum;
import com.xhh.model.reapply.dtos.AddPreapplyDto;
import com.xhh.model.reapply.dtos.GetRuleDto;
import com.xhh.model.reapply.dtos.PreapplyPageDto;
import com.xhh.model.reapply.pojos.Preapply;
import com.xhh.model.reapply.pojos.Rule;
import com.xhh.model.reapply.vos.FilterStuVo;
import com.xhh.model.user.pojos.School;
import com.xhh.model.user.pojos.Student;
import com.xhh.model.user.pojos.User;
import com.xhh.reapply.mapper.PreapplyMapper;
import com.xhh.reapply.mapper.RuleMapper;
import com.xhh.reapply.service.IPreapplyService;
import com.xhh.reapply.service.IRuleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2024-08-03
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PreapplyServiceImpl extends ServiceImpl<PreapplyMapper, Preapply> implements IPreapplyService {

    private final IUserClient userClient;
    private final RabbitTemplate rabbitTemplate;
    /**
     * 添加复试备选库
     * @param dto
     * @return
     */
    @Override
    public ResponseResult addPreapply(AddPreapplyDto dto) {
        // 1. 校验参数
        if (dto == null || dto.getReapplyId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 根据用户id获取用户名
        User user = ThreadLocalUtil.getUser();
        Long userId = user.getId();
        ResponseResult responseResult = userClient.getUserById(userId);
        if (!responseResult.getCode().equals(200) || responseResult.getData() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        String jsonString = JSON.toJSONString(responseResult.getData());
        user  = JSONObject.parseObject(jsonString, User.class);
        // 2. 添加数据
        // 2.1 判断调剂志愿状态
        if (dto.getStatus().equals(ReapplyConstants.SCANED_CHOICE_STATUS)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.CHOICE_STATUS_EXCEPTION);
        }
        // 2.1 根据准考证号获取学生基本信息
        ResponseResult result = userClient.getStuByCode(dto.getStuCode());
        if (!result.getCode().equals(200) || result.getData() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        String json = JSON.toJSONString(result.getData());
        Student student = JSONObject.parseObject(json, Student.class);
        // 2.2 添加复试备选库
        Preapply preapply = BeanUtil.copyProperties(dto, Preapply.class);
        preapply.setStuId(student.getId());
        preapply.setOperator(user.getUsername());
        preapply.setCreateTime(new Date());
        save(preapply);
        // 通知调剂志愿修改状态为已被招生单位查看 702
        try {
            rabbitTemplate.convertAndSend(
                    ReapplyConstants.EXCHANGE_NAME,
                    ReapplyConstants.SCAN_SUCCESS_KEY,
                    dto.getReapplyId()
            );
        } catch (AmqpException e) {
            log.error("已被招生单位查看的消息发送失败, 调剂志愿id：{}", dto.getReapplyId(), e);
        }
        // 3. 返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private final ICheckClient checkClient;

    /**
     * 分页查询复试备选库表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult getPreapplyByPage(PreapplyPageDto dto) {
        // 1. 分页参数校验
        dto.checkParam();
        // 校验用户身份
        User user = ThreadLocalUtil.getUser();
        ResponseResult response = checkClient.checkIdentity(user.getId());
        String json = (String) response.getData();
        CheckedVo checked = JSONObject.parseObject(json, CheckedVo.class);
        if (!checked.getIdentityCode().equals(CheckedConstants.SCHOOL_IDENTITY_CODE)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        // 获取用户名
        ResponseResult result = userClient.getUserById(user.getId());
        String s = JSON.toJSONString(result.getData());
        user = JSONObject.parseObject(s, User.class);
        // 2. 构建分页查询参数
        Page<Preapply> page = new Page<>(dto.getPage(), dto.getSize());
        page = lambdaQuery()
                .eq(Preapply::getOperator, user.getUsername())
                .eq(StrUtil.isNotEmpty(dto.getChoiceFaultyCode()), Preapply::getChoiceFaultyCode, dto.getChoiceFaultyCode())
                .eq(StrUtil.isNotEmpty(dto.getChoiceMajorCode()), Preapply::getChoiceMajorCode, dto.getChoiceMajorCode())
                .page(page);
        // 3. 返回结果
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }
}
